<template>
  <div>
    <!-- 面包屑组件 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
<el-card>
  <!-- 搜索框组件 -->
    <el-row :gutter="20">
        <el-col :span="7">
           <el-input placeholder="请输入内容" clearable  @clear="getuserList"  v-model="queryData.query">
            <el-button slot="append" icon="el-icon-search" @click="getuserList"></el-button>
          </el-input>
        </el-col>
       <el-col :span="5"> <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button></el-col>  
   </el-row>
   <!-- 表格组件 -->
   <el-table border  stripe :data="usersList" style="width: 100%">
     <el-table-column type="index"></el-table-column>
       <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>  
          <el-table-column prop="mobile" label="电话"></el-table-column> 
       <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
               <template slot-scope="item">
                  <el-switch
                  @change="editSwitch(item.row)"
                    v-model="item.row.mg_state"
                    active-color="#13ce66"
                    inactive-color="#ff4949">
                   </el-switch>
                </template>
                  </el-table-column>
                     <el-table-column  label="操作" width="180">
                         <template slot-scope="scope">
                        <el-tooltip class="item"  effect="dark" content="编辑" placement="top" :enterable="false">
                          <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDielog(scope.row.id)">  </el-button>
                        </el-tooltip>
               <el-tooltip class="item" effect="dark" content="删除" placement="top" :enterable="false"> <el-button size="mini" type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)"></el-button>  </el-tooltip>
               <el-tooltip class="item" effect="dark" content="分配任务" placement="top" :enterable="false">  <el-button size="mini" type="warning" icon="el-icon-setting"  @click="showUserDialog(scope.row)"></el-button></el-tooltip>
                 </template>
           </el-table-column>
 </el-table>
         <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryData.pagenum"
            :page-sizes="[2, 4, 8, 10]"
            :page-size="queryData.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
         </el-pagination>
</el-card>
   <!-- 添加用户对话框组件 -->
 <el-dialog
          @close="resetAddForm"
              title="添加用户"
              :visible.sync="addDialogVisible"
              width="45%">
               <el-form :model="addForm" :rules="addRule" ref="addFormRef" label-width="100px" class="demo-ruleForm">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                  </el-form-item>
                    <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                  </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                  </el-form-item>
                    <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                  </el-form-item>
               </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
              </span>
          </el-dialog>
             <!-- 编辑用户对话框 -->
      <el-dialog
             @close="resetEdit"
          title="提示"
          :visible.sync="editDialogVisible"
          width="45%">
                  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" class="demo-ruleForm">
     <el-form-item label="用户名">
           <el-input v-model="editForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
           <el-input v-model="editForm.email"></el-input>
      </el-form-item>
     <el-form-item label="电话" prop="mobile"> 
          <el-input v-model="editForm.mobile"></el-input> </el-form-item>
       </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserSub">确 定</el-button>
              </span>
            </el-dialog>

          <el-dialog
            title="分配角色"
            :visible.sync="setUsersDialogVisible"
            width="45%">
            <div>
              <p>当前的用户：{{UsersInfo.username}}</p>
                  <p> 当前的角色：{{UsersInfo.role_name}}</p>
                  <div>分配新角色：{{activeOpt}}  <el-select v-model="activeOpt" placeholder="请选择">
                                        <el-option
                                          v-for="item in rolesList"
                                          :key="item.id"
                                          :label="item.roleName"
                                          :value="item.id">
                                        </el-option>
                                      </el-select> 
                       </div>
            </div>
            <span slot="footer" class="dialog-footer">
              <el-button @click="setUsersDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="setRoluSub">确 定</el-button>
            </span>
          </el-dialog>
              </div>
       </template>


            <script>

            export default {
              data () {
                // 验证邮箱的正则
    const checkEmail = (rule,v,cb)=>{
      let reg = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
      if(reg.test(v)){
        return cb()
      }
      return cb(new Error('邮箱格式不正确'))

    }
    // 验证手机的正则
        const checkMobile = (rule,v,cb)=>{
      let reg =/^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/;
      if(reg.test(v)){
        return cb()
      }
      return cb(new Error('手机号码格式不正确'))

    }
    return {
      // 关键字和页码请求的数据
        queryData:{
            query:'',
            pagenum:1,
            pagesize:2
        },
        // 渲染用户的数据
        usersList:[],
        total:0,
        // 添加用户表单重置
        addDialogVisible:false,
        // 修改用户表单重置
        editDialogVisible:false,
        // 添加用户数据
        addForm:{
          username:'test',
          password:'123456123',
          email:'123',
          mobile:'15313113312'
        },
       editForm:{
        
       },
      //  添加用户验证
        addRule:{
          username:[
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 7, message: '长度在 2 到 7 个字符', trigger: 'blur' }
          ],
              password:[
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 9, max: 15, message: '长度在 9 到 15 个字符', trigger: 'blur' }
          ],
              email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator:checkEmail,trigger: 'blur'}
          ],
              mobile:[
            { required: true, message: '请输入手机号', trigger: 'blur' },
             {validator:checkMobile,trigger: 'blur'}
          ],
        },
        // 修改用户表单验证
        editFormRules:{
          email:[
                { required: true, message: '请输入邮箱', trigger: 'blur' },
            {validator:checkEmail,trigger: 'blur'}
          ],
          mobile:[
                { required: true, message: '请输入手机号', trigger: 'blur' },
             {validator:checkMobile,trigger: 'blur'}
          ]
        },
        setUsersDialogVisible:false,
        UsersInfo:{

        },
        rolesList:{

        },
        activeOpt:'',
    }
  },
  methods: {
    //   获取数据渲染到页面中
      async getuserList(){
        const res = await this.axios.get('/users',{
              params:this.queryData
          })
        if(res.meta.status !=200) return this.$mg.error(res.meta.msg);
         this.usersList = res.data.users
         this.total=res.data.total
      },
    //   修改状态请求
     async editSwitch (item) {
          const res = await this.axios.put(`users/${item.id}/state/${item.mg_state}`)
            if(res.meta.status ==200){
                this.$mg.success('状态修改成功')
            }else{
                this.$mg.error('状态修改失败')
            }  
      },
      // 改变每页条数
      handleSizeChange (val) {
          this.queryData.pagesize = val
          this.getuserList()
      },
      // 页码
      handleCurrentChange (val) {
          this.queryData.pagenum = val;
          this.getuserList()
      },
      resetAddForm () {
        // 获取当前组件的引用
        this.$refs.addFormRef.resetFields();
      },
      // 添加用户
      addUser () {
        // 验证表单所有的效验
        this.$refs.addFormRef.validate(async flag=>{
          if(!flag) return
          console.log('效验成功');
       const res =  await this.axios.post('users',this.addForm);
       console.log(res);
       
      if(res.meta.status == 201){
        this.$mg.success(res.meta.msg);
        this.addDialogVisible = false;
        this.getuserList()
      }else{
        this.$mg.error(res.meta.msg)
      }
      })
      },
      // 显示编辑对话框函数
     async showEditDielog (id) {
        this.editDialogVisible=true;
       const res = await this.axios.get('users/' + id)
      if(res.meta.status !== 200){
        return this.$mg.error(res.meta.msg);
      }
      // 将获取的数值赋值给editform对象
      this.editForm = res.data;
      },
      // 重置表单
    resetEdit () {
     this.$refs.editFormRef.resetFields()
    },
    // 编辑用户提交
    editUserSub () {
      this.$refs.editFormRef.validate(async falg=>{
        console.log(falg);
        if(!falg) return
        // 发送请求修改
        const res = await  this.axios.put('users/'+this.editForm.id,{
          email:this.editForm.email,
          mobile:this.editForm.mobile
        })
        console.log(res);
        if(res.meta.status !==200) return
        this.$mg.success(res.meta.msg);
        this.editDialogVisible = false;
        this.getuserList();
      })
      },
      // 删除用户数据
   delUser (id) {
         this.$cfm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(  async () => {
       const res  = await this.axios.delete('users/' +id)
       if(res.meta.status == 200){
         this.$mg.success(res.meta.msg);
         this.getuserList()
       }else{
         this.$mg.error(res.meta.msg)
       }
        }).catch(() => {
          this.$mg.info('已取消删除')   
      })
      },
      // 编辑显示分配任务对话框
    async  showUserDialog (row) {
        this.setUsersDialogVisible = true;
          this.UsersInfo = row;
         const res = await this.axios.get('roles')
        if(res.meta.status !==200)
        return this.$mg.error(res.meta.msg)
       this.rolesList = res.data
       console.log( this.rolesList)
      },
    async  setRoluSub () {
        if(!this.activeOpt) return this.$mg.error('请选择新角色');
      const res  =   await  this.axios.put(`users/${this.UsersInfo.id}/role/`,{
          rid:this.activeOpt
        })
        if(res.meta.status!==200) return this.$mg.error(res.meta.msg);
        this.$mg.success(res.meta.msg);
        this.getuserList();
        this.setUsersDialogVisible= false;
      }
  },
  created () {
      this.getuserList()
  }
}
</script>

<style lang='less' scoped>

</style>
